package cn.lvhang.basic.controller;

import cn.lvhang.basic.util.AjaxResult;
import cn.lvhang.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    // 上传接口
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true, value = "file")
                                         MultipartFile file){
        //为了获取文件后缀
        try {
            String filename = file.getOriginalFilename();
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            String path = FastDfsUtil.upload(file.getBytes(), extName);
            // /group1/M00/00/53/rBE3kWDawL6AE2ODAADyXoRe0ps872.jpg
            return AjaxResult.me().setResultObj(path);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统繁忙，稍后重试！！");
        }
    }

    // 删除接口  ?path=/group1/sfdsf/sdf/xxyy.jpg
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true, value = "path") String path){
        //为了获取文件后缀
        try {
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);
            // /group1/M00/00/53/rBE3kWDawL6AE2ODAADyXoRe0ps872.jpg
            FastDfsUtil.delete(groupName, remotePath);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统繁忙，稍后重试！！");
        }
    }

}
